package com.kantboot.api.lbs.service.impl;

import com.alibaba.fastjson2.JSON;
import com.kantboot.api.lbs.domain.entity.ApiLbsAd;
import com.kantboot.api.lbs.domain.vo.ApiLbsAreaHasAdlvVO;
import com.kantboot.api.lbs.domain.vo.ApiLbsAreaHasChildrenVO;
import com.kantboot.api.lbs.repository.ApiLbsAreaHasAdlvVORepository;
import com.kantboot.api.lbs.repository.ApiLbsAreaHasChildrenVORepository;
import com.kantboot.api.lbs.service.IApiLbsAdService;
import com.kantboot.api.lbs.service.IApiLbsAreaService;
import com.kantboot.api.lbs.util.TencentLbsUtil;
import com.kantboot.system.setting.service.ISysSettingService;
import com.kantboot.util.common.http.HttpRequestHeaderUtil;
import com.kantboot.util.core.redis.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 获取地理位置
 */
@Service
public class ApiLbsAreaServiceImpl implements IApiLbsAreaService {

    @Resource
    private ApiLbsAreaHasAdlvVORepository repository;

    @Resource
    private ApiLbsAreaHasChildrenVORepository hasChildrenVORepository;

    @Resource
    private ISysSettingService settingService;

    @Resource
    private HttpRequestHeaderUtil httpRequestHeaderUtil;

    @Resource
    private IApiLbsAdService lbsAdService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取所有
     */
    @Override
    public List<ApiLbsAreaHasChildrenVO> getAllHasChildren() {
        String key = "ApiLbs::"+"getAllHasChildren";
        String value = redisUtil.get(key);
        if (value != null) {
            return JSON.parseArray(value, ApiLbsAreaHasChildrenVO.class);
        }
        List<ApiLbsAreaHasChildrenVO> all = hasChildrenVORepository.findAll();
        redisUtil.set(key, JSON.toJSONString(all));
        return all;
    }

    @Cacheable(value = "ApiLbsArea", key = "#root.methodName")
    @Override
    public List<ApiLbsAreaHasAdlvVO> getAll() {
        return repository.findAll();
    }

    @Override
    public ApiLbsAreaHasAdlvVO getByIp(String ip) {
        String tencentMapApiKey = settingService.getValue("lbs", "tencentMapApiKey");
        ApiLbsAd lbsVO = TencentLbsUtil.byIp(ip, tencentMapApiKey);
        return repository.findByAdcode(lbsVO.getAdcode());
    }

    @Override
    public ApiLbsAreaHasAdlvVO getBySelfIp() {
        return getByIp(httpRequestHeaderUtil.getIp());
    }


    @Override
    public ApiLbsAreaHasAdlvVO getByLngAndLat(String lng, String lat) {
        String key = settingService.getValue("lbs", "tencentMapApiKey");
        ApiLbsAd lbsVO = lbsAdService.getByLngAndLat(lng, lat);
        return repository.findByAdcode(lbsVO.getAdcode());
    }
}
